package com.example.security_demo.utils;

import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 *
 * @author zzh
 * @date 2022/5/8
 * @since 1.0
 */
public class RequestParseUtil {

    /**
     * 判断当前数据类型是否为json
     * @param request 请求对象
     * @return boolean
     */
    public static boolean isJson(HttpServletRequest request) {
        if (request.getContentType() != null) {

            return request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) ||
                    request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE);
        }

        return false;
    }

    public static String getBodyString(final ServletRequest request) {

        try {
            return inputStream2String(request.getInputStream());
        } catch (IOException e) {
           throw new RuntimeException("");
        }
    }

    private static String inputStream2String(InputStream inputStream) {

        StringBuilder sb = new StringBuilder();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("");
        }

        return sb.toString();
    }
}
